<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Rails form helpers</title>
  <!--[if lt IE 8]>
  <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
  <![endif]-->
  <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
</head>
<body>
  <div id="header" >
    <div id="logo">
      <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
    </div>

    <h1 id="site_title"><span>Ruby on Rails</span></h1>
    <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>

    <ul id="navMain">
      <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
      <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
    </ul>
  </div>

  <div id="container">
    
    <div id="sidebar">
      <h2>Chapters</h2>
      <ol>
          <li>
          <a href="#_dealing_with_basic_forms">Dealing With Basic Forms</a>
            <ul>
            
              <li><a href="#_a_generic_search_form">A Generic search form</a></li>
            
              <li><a href="#_multiple_hashes_in_form_helper_calls">Multiple hashes in form helper calls</a></li>
            
              <li><a href="#_helpers_for_generating_form_elements">Helpers for generating form elements</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_dealing_with_model_objects">Dealing With Model Objects</a>
            <ul>
            
              <li><a href="#_model_object_helpers">Model object helpers</a></li>
            
              <li><a href="#_binding_a_form_to_an_object">Binding a form to an object</a></li>
            
              <li><a href="#_relying_on_record_identification">Relying on record identification</a></li>
            
              <li><a href="#_how_do_forms_with_put_or_delete_methods_work">How do forms with PUT or DELETE methods work?</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_making_select_boxes_with_ease">Making select boxes with ease</a>
            <ul>
            
              <li><a href="#_the_select_and_options_tag">The select and options tag</a></li>
            
              <li><a href="#_select_boxes_for_dealing_with_models">Select boxes for dealing with models</a></li>
            
              <li><a href="#_option_tags_from_a_collection_of_arbitrary_objects">Option tags from a collection of arbitrary objects</a></li>
            
              <li><a href="#_time_zone_and_country_select">Time zone and country select</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_using_date_and_time_form_helpers">Using Date and Time Form Helpers</a>
            <ul>
            
              <li><a href="#_barebones_helpers">Barebones helpers</a></li>
            
              <li><a href="#_model_object_helpers_2">Model object helpers</a></li>
            
              <li><a href="#_common_options">Common options</a></li>
            
              <li><a href="#_individual_components">Individual components</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_uploading_files">Uploading Files</a>
            <ul>
            
              <li><a href="#_what_gets_uploaded">What gets uploaded</a></li>
            
              <li><a href="#_dealing_with_ajax">Dealing with Ajax</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_customising_form_builders">Customising Form Builders</a>
          </li>
          <li>
          <a href="#_understanding_parameter_naming_conventions">Understanding Parameter Naming Conventions</a>
            <ul>
            
              <li><a href="#_basic_structures">Basic structures</a></li>
            
              <li><a href="#_combining_them">Combining them</a></li>
            
              <li><a href="#_using_form_helpers">Using form helpers</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_building_complex_forms">Building Complex forms</a>
          </li>
          <li>
          <a href="#_changelog">Changelog</a>
          </li>
      </ol>
    </div>
    
    <div id="content">
        <h1>Rails form helpers</h1>
      <div id="preamble">
<div class="sectionbody">
<div class="paragraph"><p>Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.</p></div>
<div class="paragraph"><p>In this guide you will:</p></div>
<div class="ulist"><ul>
<li>
<p>
Create search forms and similar kind of generic forms not representing any specific model in your application
</p>
</li>
<li>
<p>
Make model-centric forms for creation and editing of specific database records
</p>
</li>
<li>
<p>
Generate select boxes from multiple types of data
</p>
</li>
<li>
<p>
Understand the date and time helpers Rails provides
</p>
</li>
<li>
<p>
Learn what makes a file upload form different
</p>
</li>
<li>
<p>
Find out where to look for complex forms
</p>
</li>
</ul></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit <a href="http://api.rubyonrails.org/">the Rails API documentation</a> for a complete reference.</td>
</tr></table>
</div>
</div>
</div>
<h2 id="_dealing_with_basic_forms">1. Dealing With Basic Forms</h2>
<div class="sectionbody">
<div class="paragraph"><p>The most basic form helper is <tt>form_tag</tt>.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_tag do %&gt;
  Form contents
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>When called without arguments like this, it creates a form element that has the current page as its action and "post" as its method (some line breaks added for readability):</p></div>
<div class="listingblock">
<div class="title">Sample output from <tt>form_tag</tt></div>
<div class="content">
<pre><tt>&lt;form action="/home/index" method="post"&gt;
  &lt;div style="margin:0;padding:0"&gt;
    &lt;input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /&gt;
  &lt;/div&gt;
  Form contents
&lt;/form&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>If you carefully observe this output, you can see that the helper generated something you didn&#8217;t specify: a <tt>div</tt> element with a hidden input inside. This is a security feature of Rails called <strong>cross-site request forgery protection</strong> and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the <a href="./security.html#_cross_site_reference_forgery_csrf">Ruby On Rails Security Guide</a>.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">Throughout this guide, this <tt>div</tt> with the hidden input will be stripped away to have clearer code samples.</td>
</tr></table>
</div>
<h3 id="_a_generic_search_form">1.1. A Generic search form</h3>
<div class="paragraph"><p>Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of:</p></div>
<div class="olist arabic"><ol class="arabic">
<li>
<p>
a form element with "GET" method,
</p>
</li>
<li>
<p>
a label for the input,
</p>
</li>
<li>
<p>
a text input element, and
</p>
</li>
<li>
<p>
a submit element.
</p>
</li>
</ol></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/important.png" alt="Important" />
</td>
<td class="content">Always use "GET" as the method for search forms. This allows users are able to bookmark a specific search and get back to it, more generally Rails encourages you to use the right HTTP verb for an action.</td>
</tr></table>
</div>
<div class="paragraph"><p>To create this form you will use <tt>form_tag</tt>, <tt>label_tag</tt>, <tt>text_field_tag</tt> and <tt>submit_tag</tt>, respectively.</p></div>
<div class="listingblock">
<div class="title">A basic search form</div>
<div class="content">
<pre><tt>&lt;% form_tag(search_path, :method =&gt; "get") do %&gt;
  &lt;%= label_tag(:q, "Search for:") %&gt;
  &lt;%= text_field_tag(:q) %&gt;
  &lt;%= submit_tag("Search") %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">
<div class="paragraph"><p><tt>search_path</tt> can be a named route specified in "routes.rb":</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>map.search "search", :controller =&gt; "search"</tt></pre>
</div></div>
</td>
</tr></table>
</div>
<div class="paragraph"><p>The above view code will result in the following markup:</p></div>
<div class="listingblock">
<div class="title">Search form HTML</div>
<div class="content">
<pre><tt>&lt;form action="/search" method="get"&gt;
  &lt;label for="q"&gt;Search for:&lt;/label&gt;
  &lt;input id="q" name="q" type="text" /&gt;
  &lt;input name="commit" type="submit" value="Search" /&gt;
&lt;/form&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Besides <tt>text_field_tag</tt> and <tt>submit_tag</tt>, there is a similar helper for <em>every</em> form control in HTML.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">For every form input, an ID attribute is generated from its name ("q" in the example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.</td>
</tr></table>
</div>
<h3 id="_multiple_hashes_in_form_helper_calls">1.2. Multiple hashes in form helper calls</h3>
<div class="paragraph"><p>By now you&#8217;ve seen that the <tt>form_tag</tt> helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and HTML options such as the form element&#8217;s class.</p></div>
<div class="paragraph"><p>As with the &#8216;link_to` helper, the path argument doesn&#8217;t have to be given a string. It can be a hash of URL parameters that Rails&#8217; routing mechanism will turn into a valid URL. Still, you cannot simply write this:</p></div>
<div class="listingblock">
<div class="title">A bad way to pass multiple hashes as method arguments</div>
<div class="content">
<pre><tt>form_tag(:controller =&gt; "people", :action =&gt; "search", :method =&gt; "get", :class =&gt; "nifty_form")
# =&gt; &lt;form action="/people/search?method=get&amp;class=nifty_form" method="post"&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Here you wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL with extraneous parameters. The solution is to delimit the first hash (or both hashes) with curly brackets:</p></div>
<div class="listingblock">
<div class="title">The correct way of passing multiple hashes as arguments</div>
<div class="content">
<pre><tt>form_tag({:controller =&gt; "people", :action =&gt; "search"}, :method =&gt; "get", :class =&gt; "nifty_form")
# =&gt; &lt;form action="/people/search" method="get" class="nifty_form"&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an <tt>expecting tASSOC</tt> syntax error.</td>
</tr></table>
</div>
<h3 id="_helpers_for_generating_form_elements">1.3. Helpers for generating form elements</h3>
<div class="paragraph"><p>Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons and so. These basic helpers, with names ending in _tag such as <tt>text_field_tag</tt>, <tt>check_box_tag</tt> just generate a single <tt>&lt;input&gt;</tt> element. The first parameter to these is always the name of the input. In the controller, this name will be the key in the <tt>params</tt> hash used to get the value entered by the user. For example if the form contains</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= text_field_tag(:query) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>then the controller code should use</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>params[:query]</tt></pre>
</div></div>
<div class="paragraph"><p>to retrieve the value entered by the user. When naming inputs be aware that Rails uses certain conventions that control whether values are at the top level of the <tt>params</tt> hash, inside an array or a nested hash and so on. You can read more about them in the <a href="#parameter_names">parameter names</a> section. For details on the precise usage of these helpers, please refer to the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html">API documentation</a>.</p></div>
<h4 id="_checkboxes">1.3.1. Checkboxes</h4>
<div class="paragraph"><p>Checkboxes are form controls that give the user a set of options they can enable or disable:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= check_box_tag(:pet_dog) %&gt;
  &lt;%= label_tag(:pet_dog, "I own a dog") %&gt;
&lt;%= check_box_tag(:pet_cat) %&gt;
  &lt;%= label_tag(:pet_cat, "I own a cat") %&gt;

output:

&lt;input id="pet_dog" name="pet_dog" type="checkbox" value="1" /&gt;
  &lt;label for="pet_dog"&gt;I own a dog&lt;/label&gt;
&lt;input id="pet_cat" name="pet_cat" type="checkbox" value="1" /&gt;
  &lt;label for="pet_cat"&gt;I own a cat&lt;/label&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>The second parameter to <tt>check_box_tag</tt> is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the <tt>params</tt> hash). With the above form you would check the value of <tt>params[:pet_dog]</tt> and <tt>params[:pet_cat]</tt> to see which pets the user owns.</p></div>
<h4 id="_radio_buttons">1.3.2. Radio buttons</h4>
<div class="paragraph"><p>Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (user can only pick one):</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= radio_button_tag(:age, "child") %&gt;
  &lt;%= label_tag(:age_child, "I am younger than 21") %&gt;
&lt;%= radio_button_tag(:age, "adult") %&gt;
  &lt;%= label_tag(:age_adult, "I'm over 21") %&gt;

output:

&lt;input id="age_child" name="age" type="radio" value="child" /&gt;
  &lt;label for="age_child"&gt;I am younger than 21&lt;/label&gt;
&lt;input id="age_adult" name="age" type="radio" value="adult" /&gt;
  &lt;label for="age_adult"&gt;I'm over 21&lt;/label&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>As with <tt>check_box_tag</tt> the second parameter to <tt>radio_button_tag</tt> is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one and <tt>params[:age]</tt> will contain either "child" or "adult".</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/important.png" alt="Important" />
</td>
<td class="content">Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.</td>
</tr></table>
</div>
<h4 id="_other_helpers_of_interest">1.3.3. Other helpers of interest</h4>
<div class="paragraph"><p>Other form controls worth mentioning are the text area, password input and hidden input:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= text_area_tag(:message, "Hi, nice site", :size =&gt; "24x6") %&gt;
&lt;%= password_field_tag(:password) %&gt;
&lt;%= hidden_field_tag(:parent_id, "5") %&gt;

output:

&lt;textarea id="message" name="message" cols="24" rows="6"&gt;Hi, nice site&lt;/textarea&gt;
&lt;input id="password" name="password" type="password" /&gt;
&lt;input id="parent_id" name="parent_id" type="hidden" value="5" /&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">If you&#8217;re using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating <tt>filter_parameter_logging(:password)</tt> in your ApplicationController.</td>
</tr></table>
</div>
</div>
<h2 id="_dealing_with_model_objects">2. Dealing With Model Objects</h2>
<div class="sectionbody">
<h3 id="_model_object_helpers">2.1. Model object helpers</h3>
<div class="paragraph"><p>A particularly common task for a form is editing or creating a model object. While the <tt>*_tag</tt> helpers can certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the _tag suffix, for example <tt>text_field</tt>, <tt>text_area</tt>.</p></div>
<div class="paragraph"><p>For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined <tt>@person</tt> and that person&#8217;s name is Henry then a form containing:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= text_field(:person, :name) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>will produce output similar to</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;input id="person_name" name="person[name]" type="text" value="Henry"/&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Upon form submission the value entered by the user will be stored in <tt>params[:person][:name]</tt>. The <tt>params[:person]</tt> hash is suitable for passing to <tt>Person.new</tt> or, if <tt>@person</tt> is an instance of Person, <tt>@person.update_attributes</tt>. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a <tt>name</tt> and a <tt>name=</tt> method Rails will be happy.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">
<div class="paragraph"><p>You must pass the name of an instance variable, i.e. <tt>:person</tt> or <tt>"person"</tt>, not an actual instance of your model object.</p></div>
</td>
</tr></table>
</div>
<div class="paragraph"><p>Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the <a href="./activerecord_validations_callbacks.html#_using_the_tt_errors_tt_collection_in_your_view_templates">Active Record Validations and Callbacks</a> guide.</p></div>
<h3 id="_binding_a_form_to_an_object">2.2. Binding a form to an object</h3>
<div class="paragraph"><p>While this is an increase in comfort it is far from perfect. If Person has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object which is exactly what <tt>form_for</tt> does.</p></div>
<div class="paragraph"><p>Assume we have a controller for dealing with articles:</p></div>
<div class="listingblock">
<div class="title">articles_controller.rb</div>
<div class="content">
<pre><tt>def new
  @article = Article.new
end</tt></pre>
</div></div>
<div class="paragraph"><p>The corresponding view using <tt>form_for</tt> looks like this</p></div>
<div class="listingblock">
<div class="title">articles/new.html.erb</div>
<div class="content">
<pre><tt>&lt;% form_for :article, @article, :url =&gt; { :action =&gt; "create" }, :html =&gt; {:class =&gt; "nifty_form"} do |f| %&gt;
  &lt;%= f.text_field :title %&gt;
  &lt;%= f.text_area :body, :size =&gt; "60x12" %&gt;
  &lt;%= submit_tag "Create" %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>There are a few things to note here:</p></div>
<div class="olist arabic"><ol class="arabic">
<li>
<p>
<tt>:article</tt> is the name of the model and <tt>@article</tt> is the actual object being edited.
</p>
</li>
<li>
<p>
There is a single hash of options. Routing options are passed inside <tt>:url</tt> hash, HTML options are passed in the <tt>:html</tt> hash.
</p>
</li>
<li>
<p>
The <tt>form_for</tt> method yields a <strong>form builder</strong> object (the <tt>f</tt> variable).
</p>
</li>
<li>
<p>
Methods to create form controls are called <strong>on</strong> the form builder object <tt>f</tt>
</p>
</li>
</ol></div>
<div class="paragraph"><p>The resulting HTML is:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;form action="/articles/create" method="post" class="nifty_form"&gt;
  &lt;input id="article_title" name="article[title]" size="30" type="text" /&gt;
  &lt;textarea id="article_body" name="article[body]" cols="60" rows="12"&gt;&lt;/textarea&gt;
  &lt;input name="commit" type="submit" value="Create" /&gt;
&lt;/form&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>The name passed to <tt>form_for</tt> controls the key used in <tt>params</tt> to access the form&#8217;s values. Here the name is <tt>article</tt> and so all the inputs have names of the form <tt>article[attribute_name]</tt>. Accordingly, in the <tt>create</tt> action <tt>params[:article]</tt> will be a hash with keys <tt>:title</tt> and <tt>:body</tt>. You can read more about the significance of input names in the <a href="#parameter_names">parameter names</a> section.</p></div>
<div class="paragraph"><p>The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder.</p></div>
<div class="paragraph"><p>You can create a similar binding without actually creating  <tt>&lt;form&gt;</tt> tags with the <tt>fields_for</tt> helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_for :person, @person, :url =&gt; { :action =&gt; "create" } do |person_form| %&gt;
  &lt;%= person_form.text_field :name %&gt;
  &lt;% fields_for @person.contact_detail do |contact_details_form| %&gt;
    &lt;%= contact_details_form.text_field :phone_number %&gt;
  &lt;% end %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>which produces the following output:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;form action="/people/create" class="new_person" id="new_person" method="post"&gt;
  &lt;input id="person_name" name="person[name]" size="30" type="text" /&gt;
  &lt;input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" /&gt;
&lt;/form&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>The object yielded by <tt>fields_for</tt> is a form builder like the one yielded by <tt>form_for</tt> (in fact <tt>form_for</tt> calls <tt>fields_for</tt> internally).</p></div>
<h3 id="_relying_on_record_identification">2.3. Relying on record identification</h3>
<div class="paragraph"><p>The Article model is directly available to users of the application, so&#8201;&#8212;&#8201;following the best practices for developing with Rails&#8201;&#8212;&#8201;you should declare it <strong>a resource</strong>.</p></div>
<div class="paragraph"><p>When dealing with RESTful resources, calls to <tt>form_for</tt> can get significantly easier if you rely on <strong>record identification</strong>. In short, you can just pass the model instance and have Rails figure out model name and the rest:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>## Creating a new article
# long-style:
form_for(:article, @article, :url =&gt; articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)

## Editing an existing article
# long-style:
form_for(:article, @article, :url =&gt; article_path(@article), :method =&gt; "put")
# short-style:
form_for(@article)</tt></pre>
</div></div>
<div class="paragraph"><p>Notice how the short-style <tt>form_for</tt> invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking <tt>record.new_record?</tt>. It also selects the correct path to submit to and the name based on the class of the object.</p></div>
<div class="paragraph"><p>Rails will also automatically set the <tt>class</tt> and <tt>id</tt> of the form appropriately: a form creating an article would have <tt>id</tt> and <tt>class</tt> <tt>new_article</tt>. If you were editing the article with id 23 the <tt>class</tt> would be set to <tt>edit_article</tt> and the id to <tt>edit_article_23</tt>. These attributes will be omitted for brevity in the rest of this guide.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">When you&#8217;re using STI (single-table inheritance) with your models, you can&#8217;t rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, <tt>:url</tt> and <tt>:method</tt> explicitly.</td>
</tr></table>
</div>
<h4 id="_dealing_with_namespaces">2.3.1. Dealing with namespaces</h4>
<div class="paragraph"><p>If you have created namespaced routes <tt>form_for</tt> has a nifty shorthand for that too. If your application has an admin namespace then</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>form_for [:admin, @article]</tt></pre>
</div></div>
<div class="paragraph"><p>will create a form that submits to the articles controller inside the admin namespace (submitting to <tt>admin_article_path(@article)</tt> in the case of an update). If you have several levels of namespacing then the syntax is similar:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>form_for [:admin, :management, @article]</tt></pre>
</div></div>
<div class="paragraph"><p>For more information on Rails' routing system and the associated conventions, please see the <a href="./routing_outside_in.html">routing guide</a>.</p></div>
<h3 id="_how_do_forms_with_put_or_delete_methods_work">2.4. How do forms with PUT or DELETE methods work?</h3>
<div class="paragraph"><p>Rails framework encourages RESTful design of your applications, which means you&#8217;ll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers <em>don&#8217;t support</em> methods other than "GET" and "POST" when it comes to submitting forms.</p></div>
<div class="paragraph"><p>Rails works around this issue by emulating other methods over POST with a hidden input named <tt>"_method"</tt> that is set to reflect the desired method:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>form_tag(search_path, :method =&gt; "put")

output:

&lt;form action="/search" method="post"&gt;
  &lt;div style="margin:0;padding:0"&gt;
    &lt;input name="_method" type="hidden" value="put" /&gt;
    &lt;input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /&gt;
  &lt;/div&gt;
  ...</tt></pre>
</div></div>
<div class="paragraph"><p>When parsing POSTed data, Rails will take into account the special <tt>_method</tt> parameter and acts as if the HTTP method was the one specified inside it ("PUT" in this example).</p></div>
</div>
<h2 id="_making_select_boxes_with_ease">3. Making select boxes with ease</h2>
<div class="sectionbody">
<div class="paragraph"><p>Select boxes in HTML require a significant amount of markup (one <tt>OPTION</tt> element for each option to choose from), therefore it makes the most sense for them to be dynamically generated.</p></div>
<div class="paragraph"><p>Here is what the markup might look like:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;select name="city_id" id="city_id"&gt;
  &lt;option value="1"&gt;Lisbon&lt;/option&gt;
  &lt;option value="2"&gt;Madrid&lt;/option&gt;
  ...
  &lt;option value="12"&gt;Berlin&lt;/option&gt;
&lt;/select&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Here you have a list of cities whose names are presented to the user. Internally the application only wants to handle their IDs so they are used as the options' value attribute. Let&#8217;s see how Rails can help out here.</p></div>
<h3 id="_the_select_and_options_tag">3.1. The select and options tag</h3>
<div class="paragraph"><p>The most generic helper is <tt>select_tag</tt>, which&#8201;&#8212;&#8201;as the name implies&#8201;&#8212;&#8201;simply generates the <tt>SELECT</tt> tag that encapsulates an options string:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= select_tag(:city_id, '&lt;option value="1"&gt;Lisbon&lt;/option&gt;...') %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>This is a start, but it doesn&#8217;t dynamically create the option tags. You can generate option tags with the <tt>options_for_select</tt> helper:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %&gt;

output:

&lt;option value="1"&gt;Lisbon&lt;/option&gt;
&lt;option value="2"&gt;Madrid&lt;/option&gt;
...</tt></pre>
</div></div>
<div class="paragraph"><p>The first argument to <tt>options_for_select</tt> is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case.</p></div>
<div class="paragraph"><p>Knowing this, you can combine <tt>select_tag</tt> and <tt>options_for_select</tt> to achieve the desired, complete markup:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= select_tag(:city_id, options_for_select(...)) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p><tt>options_for_select</tt> allows you to pre-select an option by passing its value.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %&gt;

output:

&lt;option value="1"&gt;Lisbon&lt;/option&gt;
&lt;option value="2" selected="selected"&gt;Madrid&lt;/option&gt;
...</tt></pre>
</div></div>
<div class="paragraph"><p>Whenever Rails sees that the internal value of an option being generated matches this value, it will add the <tt>selected</tt> attribute to that option.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">
<div class="paragraph"><p>The second argument to <tt>options_for_select</tt> must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to <tt>options_for_select</tt>&#8201;&#8212;&#8201;you must pass 2. Be aware of values extracted from the <tt>params</tt> hash as they are all strings.</p></div>
</td>
</tr></table>
</div>
<h3 id="_select_boxes_for_dealing_with_models">3.2. Select boxes for dealing with models</h3>
<div class="paragraph"><p>In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the <tt>_tag</tt> suffix from <tt>select_tag</tt>:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt># controller:
@person = Person.new(:city_id =&gt; 2)

# view:
&lt;%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Notice that the third parameter, the options array, is the same kind of argument you pass to <tt>options_for_select</tt>. One advantage here is that you don&#8217;t have to worry about pre-selecting the correct city if the user already has one&#8201;&#8212;&#8201;Rails will do this for you by reading from the <tt>@person.city_id</tt> attribute.</p></div>
<div class="paragraph"><p>As with other helpers, if you were to use <tt>select</tt> helper on a form builder scoped to <tt>@person</tt> object, the syntax would be:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt># select on a form builder
&lt;%= f.select(:city_id, ...) %&gt;</tt></pre>
</div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">
<div class="paragraph"><p>If you are using <tt>select</tt> (or similar helpers such as <tt>collection_select</tt>, <tt>select_tag</tt>) to set a <tt>belongs_to</tt> association you must pass the name of the foreign key (in the example above <tt>city_id</tt>), not the name of association itself.</p></div>
<div class="paragraph"><p>If you specify <tt>city</tt> instead of <tt>city_id</tt> Active Record will raise an error along the lines of</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750)</tt></pre>
</div></div>
<div class="paragraph"><p>when you pass the <tt>params</tt> hash to <tt>Person.new</tt> or <tt>update_attributes</tt>. Another way of looking at this is that form helpers only edit attributes.</p></div>
<div class="paragraph"><p>You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of <tt>attr_protected</tt> and <tt>attr_accessible</tt>. For further details on this, see the <a href="security.html#_mass_assignment">Ruby On Rails Security Guide</a>.</p></div>
</td>
</tr></table>
</div>
<h3 id="_option_tags_from_a_collection_of_arbitrary_objects">3.3. Option tags from a collection of arbitrary objects</h3>
<div class="paragraph"><p>Generating options tags with <tt>options_for_select</tt> requires that you create an array containing the text and value for each option. But what if you had a City model (perhaps an Active Record one) and you wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% cities_array = City.all.map { |city| [city.name, city.id] } %&gt;
&lt;%= options_for_select(cities_array) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>This is a perfectly valid solution, but Rails provides a less verbose alternative: <tt>options_from_collection_for_select</tt>. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option <strong>value</strong> and <strong>text</strong> from, respectively:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= options_from_collection_for_select(City.all, :id, :name) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with <tt>select_tag</tt>, just as you would with <tt>options_for_select</tt>. When working with model objects, just as <tt>select</tt> combines <tt>select_tag</tt> and <tt>options_for_select</tt>, <tt>collection_select</tt> combines <tt>select_tag</tt> with <tt>options_from_collection_for_select</tt>.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= collection_select(:person, :city_id, City.all, :id, :name) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>To recap, <tt>options_from_collection_for_select</tt> is to <tt>collection_select</tt> what <tt>options_for_select</tt> is to <tt>select</tt>.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">
<div class="paragraph"><p>Pairs passed to <tt>options_for_select</tt> should have the name first and the id second, however with <tt>options_from_collection_for_select</tt> the first argument is the value method and the second the text method.</p></div>
</td>
</tr></table>
</div>
<h3 id="_time_zone_and_country_select">3.4. Time zone and country select</h3>
<div class="paragraph"><p>To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using <tt>collection_select</tt>, but you can simply use the <tt>time_zone_select</tt> helper that already wraps this:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= time_zone_select(:person, :time_zone) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>There is also <tt>time_zone_options_for_select</tt> helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.</p></div>
<div class="paragraph"><p>Rails <em>used</em> to have a <tt>country_select</tt> helper for choosing countries but this has been extracted to the <a href="http://github.com/rails/country_select/tree/master">country_select plugin</a>. When using this do be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from rails).</p></div>
</div>
<h2 id="_using_date_and_time_form_helpers">4. Using Date and Time Form Helpers</h2>
<div class="sectionbody">
<div class="paragraph"><p>The date and time helpers differ from all the other form helpers in two important respects:</p></div>
<div class="olist arabic"><ol class="arabic">
<li>
<p>
Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your <tt>params</tt> hash with your date or time.
</p>
</li>
<li>
<p>
Other helpers use the _tag suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, <tt>select_date</tt>, <tt>select_time</tt> and <tt>select_datetime</tt> are the barebones helpers, <tt>date_select</tt>, <tt>time_select</tt> and <tt>datetime_select</tt> are the equivalent model object helpers.
</p>
</li>
</ol></div>
<div class="paragraph"><p>Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).</p></div>
<h3 id="_barebones_helpers">4.1. Barebones helpers</h3>
<div class="paragraph"><p>The <tt>select_*</tt> family of helpers take as their first argument an instance of Date, Time or DateTime that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= select_date Date.today, :prefix =&gt; :start_date %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>outputs (with actual option values omitted for brevity)</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;select id="start_date_year" name="start_date[year]"&gt; ... &lt;/select&gt;
&lt;select id="start_date_month" name="start_date[month]"&gt; ... &lt;/select&gt;
&lt;select id="start_date_day" name="start_date[day]"&gt; ... &lt;/select&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>The above inputs would result in <tt>params[:start_date]</tt> being a hash with keys <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>. To get an actual Time or Date object you would have to extract these values and pass them to the appropriate constructor, for example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)</tt></pre>
</div></div>
<div class="paragraph"><p>The <tt>:prefix</tt> option is the key used to retrieve the hash of date components from the <tt>params</tt> hash. Here it was set to <tt>start_date</tt>, if omitted it will default to <tt>date</tt>.</p></div>
<h3 id="_model_object_helpers_2">4.2. Model object helpers</h3>
<div class="paragraph"><p><tt>select_date</tt> does not work well with forms that update or create Active Record objects as Active Record expects each element of the <tt>params</tt> hash to correspond to one attribute.
The model object helpers for dates and times submit parameters with special names,  when Active Record sees parameters with such names it knows they must be combined with the other parameters and given to a constructor appropriate to the column type. For example:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= date_select :person, :birth_date %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>outputs (with actual option values omitted for brevity)</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;select id="person_birth_date_1i" name="person[birth_date(1i)]"&gt; ... &lt;/select&gt;
&lt;select id="person_birth_date_2i" name="person[birth_date(2i)]"&gt; ... &lt;/select&gt;
&lt;select id="person_birth_date_3i" name="person[birth_date(3i)]"&gt; ... &lt;/select&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>which results in a <tt>params</tt> hash like</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>{:person =&gt; {'birth_date(1i)' =&gt; '2008', 'birth_date(2i)' =&gt; '11', 'birth_date(3i)' =&gt; '22'}}</tt></pre>
</div></div>
<div class="paragraph"><p>When this is passed to <tt>Person.new</tt> (or <tt>update_attributes</tt>), Active Record spots that these parameters should all be used to construct the <tt>birth_date</tt> attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as <tt>Date.civil</tt>.</p></div>
<h3 id="_common_options">4.3. Common options</h3>
<div class="paragraph"><p>Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the <tt>:start_year</tt> and <tt>:end_year</tt> options override this. For an exhaustive list of the available options, refer to the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html">API documentation</a>.</p></div>
<div class="paragraph"><p>As a rule of thumb you should be using <tt>date_select</tt> when working with model objects and <tt>select_date</tt> in others cases, such as a search form which filters results by date.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">In many cases the built in date pickers are clumsy as they do not aid the user in working out the relationship between the date and the day of the week.</td>
</tr></table>
</div>
<h3 id="_individual_components">4.4. Individual components</h3>
<div class="paragraph"><p>Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component <tt>select_year</tt>, <tt>select_month</tt>, <tt>select_day</tt>, <tt>select_hour</tt>, <tt>select_minute</tt>, <tt>select_second</tt>. These helpers are fairly straightforward. By default they will generate a input named after the time component (for example "year" for <tt>select_year</tt>, "month" for <tt>select_month</tt> etc.) although this can be overriden with the  <tt>:field_name</tt> option. The <tt>:prefix</tt> option works in the same way that it does for <tt>select_date</tt> and <tt>select_time</tt> and has the same default value.</p></div>
<div class="paragraph"><p>The first parameter specifies which value should be selected and can either be an instance of a Date, Time or DateTime, in which case the relevant component will be extracted, or a numerical value. For example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= select_year(2009) %&gt;
&lt;%= select_year(Time.now) %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by <tt>params[:date][:year]</tt>.</p></div>
</div>
<h2 id="_uploading_files">5. Uploading Files</h2>
<div class="sectionbody">
<div class="paragraph"><p>A common task is uploading some sort of file, whether it&#8217;s a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the form&#8217;s encoding <strong>MUST</strong> be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing <tt>:multi_part =&gt; true</tt> as an HTML option. This means that in the case of <tt>form_tag</tt> it must be passed in the second options hash and in the case of <tt>form_for</tt> inside the <tt>:html</tt> hash.</p></div>
<div class="paragraph"><p>The following two forms both upload a file.</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_tag({:action =&gt; :upload}, :multipart =&gt; true) do %&gt;
  &lt;%= file_field_tag 'picture' %&gt;
&lt;% end %&gt;

&lt;% form_for @person, :html =&gt; {:multipart =&gt; true} do |f| %&gt;
  &lt;%= f.file_field :picture %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Rails provides the usual pair of helpers: the barebones <tt>file_field_tag</tt> and the model oriented <tt>file_field</tt>. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in <tt>params[:picture]</tt> and in the second case in <tt>params[:person][:picture]</tt>.</p></div>
<h3 id="_what_gets_uploaded">5.1. What gets uploaded</h3>
<div class="paragraph"><p>The object in the <tt>params</tt> hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file. In both cases the object will have an <tt>original_filename</tt> attribute containing the name the file had on the user&#8217;s computer and a <tt>content_type</tt> attribute containing the MIME type of the uploaded file. The following snippet saves the uploaded content in <tt>#{Rails.root}/public/uploads</tt> under the same name as the original file (assuming the form was the one in the previous example).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> upload
  uploaded_io <span style="color: #990000">=</span> params<span style="color: #990000">[:</span>person<span style="color: #990000">][:</span>picture<span style="color: #990000">]</span>
  File<span style="color: #990000">.</span>open<span style="color: #990000">(</span>Rails<span style="color: #990000">.</span>root<span style="color: #990000">.</span>join<span style="color: #990000">(</span><span style="color: #FF0000">'public'</span><span style="color: #990000">,</span> <span style="color: #FF0000">'uploads'</span><span style="color: #990000">,</span> uploaded_io<span style="color: #990000">.</span>original_filename<span style="color: #990000">),</span> <span style="color: #FF0000">'w'</span><span style="color: #990000">)</span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>file<span style="color: #990000">|</span>
    file<span style="color: #990000">.</span>write<span style="color: #990000">(</span>uploaded_io<span style="color: #990000">.</span>read<span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Once a file has been uploaded there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several plugins designed to assist with these. Two of the better known ones are <a href="http://github.com/technoweenie/attachment_fu">Attachment-Fu</a> and <a href="http://www.thoughtbot.com/projects/paperclip">Paperclip</a>.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">If the user has not selected a file the corresponding parameter will be an empty string.</td>
</tr></table>
</div>
<h3 id="_dealing_with_ajax">5.2. Dealing with Ajax</h3>
<div class="paragraph"><p>Unlike other forms making an asynchronous file upload form is not as simple as replacing <tt>form_for</tt> with <tt>remote_form_for</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.</p></div>
</div>
<h2 id="_customising_form_builders">6. Customising Form Builders</h2>
<div class="sectionbody">
<div class="paragraph"><p>As mentioned previously the object yielded by <tt>form_for</tt> and <tt>fields_for</tt> is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_for @person do |f| %&gt;
  &lt;%= text_field_with_label f, :first_name %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>can be replaced with</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_for @person, :builder =&gt; LabellingFormBuilder do |f| %&gt;
  &lt;%= f.text_field :first_name %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>by defining a LabellingFormBuilder class similar to the following:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LabellingFormBuilder <span style="color: #990000">&lt;</span> FormBuilder
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> text_field<span style="color: #990000">(</span>attribute<span style="color: #990000">,</span> options<span style="color: #990000">=</span><span style="color: #FF0000">{}</span><span style="color: #990000">)</span>
    label<span style="color: #990000">(</span>attribute<span style="color: #990000">)</span> <span style="color: #990000">+</span> text_field<span style="color: #990000">(</span>attribute<span style="color: #990000">,</span> options<span style="color: #990000">)</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you reuse this frequently you could define a <tt>labeled_form_for</tt> helper that automatically applies the <tt>:builder =&gt; LabellingFormBuilder</tt> option.</p></div>
<div class="paragraph"><p>The form builder used also determines what happens when you do</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;%= render :partial =&gt; f %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>If <tt>f</tt> is an instance of FormBuilder then this will render the <tt>form</tt> partial, setting the partial&#8217;s object to the form builder. If the form builder is of class LabellingFormBuilder then the <tt>labelling_form</tt> partial would be rendered instead.</p></div>
</div>
<h2 id="_understanding_parameter_naming_conventions">7. Understanding Parameter Naming Conventions</h2>
<div class="sectionbody">
<div class="paragraph" id="parameter_names"><p>As you&#8217;ve seen in the previous sections, values from forms can be at the top level of the <tt>params</tt> hash or nested in another hash. For example in a standard <tt>create</tt>
action for a Person model, <tt>params[:model]</tt> would usually be a hash of all the attributes for the person to create. The <tt>params</tt> hash can also contain arrays, arrays of hashes and so on.</p></div>
<div class="paragraph"><p>Fundamentally HTML forms don&#8217;t know about any sort of structured data, all they generate is name-value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">
<div class="paragraph"><p>You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&amp;phone=0123456789"
# =&gt; {"name"=&gt;"fred", "phone"=&gt;"0123456789"}</tt></pre>
</div></div>
</td>
</tr></table>
</div>
<h3 id="_basic_structures">7.1. Basic structures</h3>
<div class="paragraph"><p>The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in <tt>params</tt>. For example if a form contains</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;input id="person_name" name="person[name]" type="text" value="Henry"/&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>the <tt>params</tt> hash will contain</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>{'person' =&gt; {'name' =&gt; 'Henry'}}</tt></pre>
</div></div>
<div class="paragraph"><p>and <tt>params["name"]</tt> will retrieve the submitted value in the controller.</p></div>
<div class="paragraph"><p>Hashes can be nested as many levels as required, for example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;input id="person_address_city" name="person[address][city]" type="text" value="New York"/&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>will result in the <tt>params</tt> hash being</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>{'person' =&gt; {'address' =&gt; {'city' =&gt; 'New York'}}}</tt></pre>
</div></div>
<div class="paragraph"><p>Normally Rails ignores duplicate parameter names. If the parameter name contains [] then they will be accumulated in an array. If you wanted people to be able to input multiple phone numbers, your could place this in the form:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;input name="person[phone_number][]" type="text"/&gt;
&lt;input name="person[phone_number][]" type="text"/&gt;
&lt;input name="person[phone_number][]" type="text"/&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>This would result in <tt>params[:person][:phone_number]</tt> being an array.</p></div>
<h3 id="_combining_them">7.2. Combining them</h3>
<div class="paragraph"><p>We can mix and match these two concepts. For example, one element of a hash might be an array as in the previous example, or you can have an array of hashes. For example a form might let you create any number of addresses by repeating the following form fragment</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;input name="addresses[][line1]" type="text"/&gt;
&lt;input name="addresses[][line2]" type="text"/&gt;
&lt;input name="addresses[][city]" type="text"/&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>This would result in <tt>params[:addresses]</tt> being an array of hashes with keys <tt>line1</tt>, <tt>line2</tt> and <tt>city</tt>. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash.</p></div>
<div class="paragraph"><p>There&#8217;s a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can be usually replaced by hashes, for example instead of having an array of model objects one can have a hash of model objects keyed by their id, an array index or some other parameter.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">Array parameters do not play well with the <tt>check_box</tt> helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The <tt>check_box</tt> helper fakes this by creating a second hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use <tt>check_box_tag</tt> or to use hashes instead of arrays.</td>
</tr></table>
</div>
<h3 id="_using_form_helpers">7.3. Using form helpers</h3>
<div class="paragraph"><p>The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as <tt>text_field_tag</tt> Rails also provides higher level support. The two tools at your disposal here are the name parameter to <tt>form_for</tt> and <tt>fields_for</tt> and the <tt>:index</tt> option that helpers take.</p></div>
<div class="paragraph"><p>You might want to render a form with a set of edit fields for each of a person&#8217;s addresses. For example:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% form_for @person do |person_form| %&gt;
  &lt;%= person_form.text_field :name %&gt;
  &lt;% for address in @person.addresses %&gt;
    &lt;% person_form.fields_for address, :index =&gt; address do |address_form|%&gt;
      &lt;%= address_form.text_field :city %&gt;
    &lt;% end %&gt;
  &lt;% end %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;form action="/people/1" class="edit_person" id="edit_person_1" method="post"&gt;
  &lt;input id="person_name" name="person[name]" size="30" type="text" /&gt;
  &lt;input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" /&gt;
  &lt;input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" /&gt;
&lt;/form&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>This will result in a <tt>params</tt> hash that looks like</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>{'person' =&gt; {'name' =&gt; 'Bob', 'address' =&gt; {'23' =&gt; {'city' =&gt; 'Paris'}, '45' =&gt; {'city' =&gt; 'London'}}}}</tt></pre>
</div></div>
<div class="paragraph"><p>Rails knows that all these inputs should be part of the person hash because you called <tt>fields_for</tt> on the first form builder. By specifying an <tt>:index</tt> option you&#8217;re telling rails that instead of naming the inputs <tt>person[address][city]</tt> it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call <tt>to_param</tt> on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even <tt>nil</tt> (which will result in an array parameter being created).</p></div>
<div class="paragraph"><p>To create more intricate nestings, you can specify the first part of the input name (<tt>person[address]</tt> in the previous example) explicitly, for example</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% fields_for 'person[address][primary]', address, :index =&gt; address do |address_form| %&gt;
  &lt;%= address_form.text_field :city %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>will create inputs like</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" /&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>As a general rule the final input name is the concatenation of the name given to <tt>fields_for</tt>/<tt>form_for</tt>, the index value and the name of the attribute. You can also pass an <tt>:index</tt> option directly to helpers such as <tt>text_field</tt>, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls.</p></div>
<div class="paragraph"><p>As a shortcut you can append [] to the name and omit the <tt>:index</tt> option. This is the same as specifing <tt>:index =&gt; address</tt> so</p></div>
<div class="listingblock">
<div class="content">
<pre><tt>&lt;% fields_for 'person[address][primary][]', address do |address_form| %&gt;
  &lt;%= address_form.text_field :city %&gt;
&lt;% end %&gt;</tt></pre>
</div></div>
<div class="paragraph"><p>produces exactly the same output as the previous example.</p></div>
</div>
<h2 id="_building_complex_forms">8. Building Complex forms</h2>
<div class="sectionbody">
<div class="paragraph"><p>Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:</p></div>
<div class="ulist"><ul>
<li>
<p>
Ryan Bates' series of railscasts on <a href="http://railscasts.com/episodes/75">complex forms</a>
</p>
</li>
<li>
<p>
Handle Multiple Models in One Form from <a href="http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf">Advanced Rails Recipes</a>
</p>
</li>
<li>
<p>
Eloy Duran&#8217;s <a href="http://github.com/alloy/complex-form-examples/tree/alloy-nested_params">nested_params</a> plugin
</p>
</li>
<li>
<p>
Lance Ivy&#8217;s <a href="http://github.com/cainlevy/nested_assignment/tree/master">nested_assignment</a> plugin and <a href="http://github.com/cainlevy/complex-form-examples/tree/cainlevy">sample application</a>
</p>
</li>
<li>
<p>
James Golick&#8217;s <a href="http://github.com/giraffesoft/attribute_fu/tree">attribute_fu</a> plugin
</p>
</li>
</ul></div>
</div>
<h2 id="_changelog">9. Changelog</h2>
<div class="sectionbody">
<div class="paragraph"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/1">Lighthouse ticket</a></p></div>
<div class="ulist"><div class="title">Authors</div><ul>
<li>
<p>
Mislav Marohnić &lt;<a href="mailto:mislav.marohnic@gmail.com">mislav.marohnic@gmail.com</a>&gt;
</p>
</li>
<li>
<p>
<a href="../authors.html#fcheung">Frederick Cheung</a>
</p>
</li>
</ul></div>
</div>

    </div>
  </div>
</body>
</html>
